<?php

namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\Items;
use App\Cates;
use App\Models;
use App\Brands;
use App\Companies;
use App\Province;
use App\City;
use App\Area;
use App\Item_images;
use App\Item_attr;
use Image;
use Excel;
use Redirect;

class ItemController extends Controller
{
	public $cates  = null;
	public $brands = null;	
	public $companies = null;
	public $province  = null;
	public $pageSize = null;
	
	
	
	public function __construct()
	{
		$this->cates  = (new Cates)->getTree((new Cates)->getAllCates());
		$this->brands = (new Brands)->getAllBrands();	
		$this->companies = (new Companies)->getAll();	
		$this->province = Province::All();	
		$this->pageSize	 = CS('admin_page_size')!=''?CS('admin_page_size'):20;
	}
	
	

	/**
	 * 获取商品列表
	 */
	public function index(Request $req)
	{
		//权限验证
		if(!in_array('item_list',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}

		$title  = trans('admin.item_list');
		$models = [];
		$bin	= Items::where('is_show',1)->count();
		$item_id	=	isset($req->item_id)?trim($req->item_id):'';
		$item_sn	=	isset($req->item_sn)?trim($req->item_sn):'';
		$cat_id		=	isset($req->cat_id)?trim($req->cat_id):'';
		$com_id		=	isset($req->com_id)?trim($req->com_id):'';
		$brand_id	=	isset($req->brand_id)?trim($req->brand_id):'';
		$model_id	=	isset($req->model_id)?trim($req->model_id):'';
		$status		=	isset($req->status)?trim($req->status):'';
		$is_sale	=	isset($req->is_sale)?trim($req->is_sale):'';
		$is_hot		=	isset($req->is_hot)?trim($req->is_hot):'';
		$keyword	=	isset($req->keyword)?trim($req->keyword):'';
		$where 	 = ['items.is_show'=>0];
				
		if($item_id !== '')
		{
			$where   = array_merge($where, ['items.item_id' => $item_id]);
		}
		
		if($item_sn !== '')
		{
			$where   = array_merge($where, ['items.item_sn' => $item_sn]);
		}
		
		
		if($com_id !== '')
		{
			$where   = array_merge($where, ['items.com_id' => $com_id]);
		}
		
		if($brand_id !== '')
		{
			$where   = array_merge($where, ['items.brand_id' => $brand_id]);
			$models	 = Models::where('brand_id',$brand_id)->get();
		}
		
		if($model_id !== '')
		{
			$where   = array_merge($where, ['items.model_id' => $model_id]);
		}
		
		if($status !== '')
		{
			$where   = array_merge($where, ['items.status' => $status]);
		}
		
		if($is_sale !== '')
		{
			$where   = array_merge($where, ['items.is_sale' => $is_sale]);
		}
		
		if($is_hot !== '')
		{
			$where   = array_merge($where, ['items.is_hot' => $is_hot]);
		}
		
		if($cat_id !== '' && $keyword !== '')
		{
			$child = [$cat_id];
			$child = array_merge($child,(new Cates)->getChild($cat_id));
			$data = Items::leftJoin('cates', 'items.cat_id', '=', 'cates.cat_id')
			->leftJoin('brands', 'items.brand_id',  '=', 'brands.brand_id')
			->leftJoin('models', 'items.model_id',  '=', 'models.model_id')
			->leftJoin('companies', 'items.com_id', '=', 'companies.com_id')
			->select('items.*','brands.brand_name','models.model','cates.cat_name','companies.com_name')
			->where($where)
			->where('items.keyword','like','%'.$keyword.'%')
			->whereIn('cates.cat_id',$child)
			->orderBy('items.item_id','desc')
	        ->paginate($this -> pageSize);				
		}
		else if($cat_id !== '')
		{
			$child = [$cat_id];
			$child = array_merge($child,(new Cates)->getChild($cat_id));
			$data = Items::leftJoin('cates', 'items.cat_id', '=', 'cates.cat_id')
			->leftJoin('brands', 'items.brand_id',  '=', 'brands.brand_id')
			->leftJoin('models', 'items.model_id',  '=', 'models.model_id')
			->leftJoin('companies', 'items.com_id', '=', 'companies.com_id')
			->select('items.*','brands.brand_name','models.model','cates.cat_name','companies.com_name')
			->where($where)
			->whereIn('cates.cat_id',$child)
			->orderBy('items.item_id','desc')
	        ->paginate($this -> pageSize);				
		}
		else if($keyword !== '')
		{
			$data = Items::leftJoin('cates', 'items.cat_id', '=', 'cates.cat_id')
			->leftJoin('brands', 'items.brand_id',  '=', 'brands.brand_id')
			->leftJoin('models', 'items.model_id',  '=', 'models.model_id')
			->leftJoin('companies', 'items.com_id', '=', 'companies.com_id')
			->select('items.*','brands.brand_name','models.model','cates.cat_name','companies.com_name')
			->where($where)
			->where('items.keyword','like','%'.$keyword.'%')
			->orderBy('items.item_id','desc')
	        ->paginate($this -> pageSize);					
		}
		else
		{
			$data = Items::leftJoin('cates', 'items.cat_id', '=', 'cates.cat_id')
			->leftJoin('brands', 'items.brand_id',  '=', 'brands.brand_id')
			->leftJoin('models', 'items.model_id',  '=', 'models.model_id')
			->leftJoin('companies', 'items.com_id', '=', 'companies.com_id')
			->select('items.*','brands.brand_name','models.model','cates.cat_name','companies.com_name')
			->where($where)
			->orderBy('items.item_id','desc')
	        ->paginate($this -> pageSize);		
		}

		return view('admin.item.item_list',['title'=>$title,
			'bin'		=> 	$bin,
			'cates'		=>	$this->cates,
			'brands'	=>	$this->brands,
			'companies'	=>	$this->companies,
			'models'	=>  $models, 
			'data'		=>	$data,
			'item_id'	=>	$item_id,
			'item_sn'	=>	$item_sn,
			'cat_id'	=>	$cat_id	,
			'com_id'	=>	$com_id	,
		    'brand_id'	=>	$brand_id,
		    'model_id'	=>	$model_id,
			'status'	=>	$status	,
		    'is_sale'	=>	$is_sale,
			'is_hot'	=>	$is_hot	,
		    'keyword'	=>	$keyword,
		]);
	}





	/**
	 * 添加商品 
	 */
	public function add(Request $req)
	{
		//权限验证
		if(!in_array('item_add',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}

		if($req->isMethod('get'))
		{
			$title  = trans('admin.item_add');
			return view('admin.item.item_add',['title'=>$title,
				'cates'		=>	$this->cates,
				'province'  =>  $this->province,
				'brands'	=>	$this->brands,
				'companies'	=>	$this->companies,
			]);			
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'item_name' => 'required|max:100',
	            'cat_id'    => 'required|integer|not_in:0',
	            'number'    => 'required|integer',
	            'market_price'    => 'required|numeric',
	            'price'    		  => 'required|numeric',
	            'click'    		  => 'integer',
	            'status'		  => 'required',
	            'is_sale'		  => 'required',
	            'is_hot'		  => 'required',
	        ];
	        $message = [
	            'item_name.required' => '商品名称不能为空',
				'item_name.max' 	 => '商品名称长度不能大于100',
				'cat_id.required' 	 => '请选择栏目',
				'cat_id.integer'	 => '栏目id为整型',
				'cat_id.not_in'		 => '栏目不能为顶级分类',
				'number.required' 	 => '库存不能为空',
				'number.integer'	 => '库存为数字',
				'market_price.required' => '市场价不能为空',
				'price.required' => '价格不能为空',
				'market_price.integer'	 => '市场价为数字',
				'price.integer'			 => '价格为数字',
				'click.integer'	 	 	=> '点击次数为数字',
				'status.required'		=>'请选择状态',
	            'is_sale.required'      =>'请选择是否上架',
	            'is_hot.required'       =>'请选择是否热销',		
	        ];
	
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }

			//写入商品数据
			$sn = $this->getSn($input);
			$desc = isset($input['desc'])?$input['desc']:'';
			$item_id = Items::insertGetId(['item_name' => trim($req->item_name),
				'item_sn'		=> $sn,
				'cat_id'		=> trim($req->cat_id),
				'brand_id'		=> trim($req->brand_id),
				'com_id'		=> trim($req->com_id),
				'price' 		=> trim($req->price),
				'market_price' 	=> trim($req->market_price),
				'number' 		=> trim($req->number),
				'model_id' 		=> trim($req->model_id),
				'province_id' 	=> trim($req->province_id),
				'city_id' 		=> trim($req->city_id),
				'area_id' 		=> trim($req->area_id),
				'status' 		=> trim($req->status),
				'is_show' 		=> 0,
				'is_sale' 		=> trim($req->is_sale),
				'is_hot' 		=> trim($req->is_hot),
				'sort_order' 	=> trim($req->sort_order),
				'keyword' 		=> $this->getKeyword($input,$sn),
				'desc' 			=> $desc,
				'click' 		=> trim($req->click),
				'sales_number' 	=> trim($req->sales_number),
				'create_at' 	=> time(),
				'update_at'  	=> time()
			]);
			

			//商品图片处理
			$path = 'uploads/items/'.date('Y/m/d/');
			if(!is_dir($path))
			{
				mkdir($path,0777,true);
			}
			
			if(CS('watermark')!='' && CS('wm_switch') == 0)
			{
				foreach($input['img'] as $k => $i)
				{
					if($i != '')
					{
						$img_ori	 = Image::make($i);
				        $_oriPath    = $path.rand(1111,9999).'_'.strRand(4).'.jpg';
						$img_ori->insert(public_path(CS('watermark')), 'bottom-right');
		    			$img_ori->save($_oriPath);
		    			
						$img_big	 = Image::make($i)->resize(500, 500);
				        $_bigPath    = $path.rand(1111,9999).'_'.strRand(4).'_500x500'.'.jpg';
						$img_big->insert(public_path(CS('watermark')), 'bottom-right');
		    			$img_big->save($_bigPath);				
						
				        $img_little  = Image::make($i)->resize(200, 200);
				        $_littlePath = $path.rand(1111,9999).'_'.strRand(4).'_200x200'.'.jpg';
						$img_little->insert(public_path(CS('watermark')), 'bottom-right');
		    			$img_little->save($_littlePath);
		    			
		    			$img_tiny  = Image::make($i)->resize(100, 100);
				        $_tinyPath  = $path.rand(1111,9999).'_'.strRand(4).'_100x100'.'.jpg';
						$img_tiny->insert(public_path(CS('watermark')), 'bottom-right');
		    			$img_tiny->save($_tinyPath);
		    					
		    			Item_images::insert([
		    				'item_id' 		=> $item_id,
		    				'img_desc'		=> $input['img_desc'][$k],
		    				'ori_img' 		=> $_oriPath,
		    				'big_img'		=> $_bigPath,
		    				'little_img' 	=> $_littlePath,
		    				'tiny_img'		=> $_tinyPath,
		    			]);						
					}
				}												
			}
			else
			{
				foreach($input['img'] as $k => $i)
				{
					if($i != '')
					{
						$img_ori	 = Image::make($i);
				        $_oriPath  = $path.rand(1111,9999).'_'.strRand(4).'.jpg';
		    			$img_ori->save($_oriPath);
		    			
						$img_big	 = Image::make($i)->resize(500, 500);
				        $_bigPath  = $path.rand(1111,9999).'_'.strRand(4).'_500x500'.'.jpg';
		    			$img_big->save($_bigPath);				
						
				        $img_little  = Image::make($i)->resize(200, 200);
				        $_littlePath  = $path.rand(1111,9999).'_'.strRand(4).'_200x200'.'.jpg';
		    			$img_little->save($_littlePath);
		    			
		    			$img_tiny  = Image::make($i)->resize(100, 100);
				        $_tinyPath  = $path.rand(1111,9999).'_'.strRand(4).'_100x100'.'.jpg';
		    			$img_tiny->save($_tinyPath);
		    					
		    			Item_images::insert([
		    				'item_id' 		=> $item_id,
		    				'img_desc'		=> $input['img_desc'][$k],
		    				'ori_img' 		=> $_oriPath,
		    				'big_img'		=> $_bigPath,
		    				'little_img' 	=> $_littlePath,
		    				'tiny_img'		=> $_tinyPath,
		    			]);						
					}
				}								
			}	

			//商品属性处理
			foreach($input['attr_name'] as $k => $v)
			{	if($v != '')
				{
	    			Item_attr::insert([
    					'item_id' 		=> $item_id,
						'attr_name'		=> $v,
						'attr_value'   	=> $input['attr_value'][$k],
    				]);		
				}			
			}
			

			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.add_succ'),
				'url' => url('admin/item')
			]);



		}

	}





	/**
	 * 获取商品回收站列表
	 */
	public function bin(Request $req)
	{
		//权限验证
		if(!in_array('item_bin',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		
		$title  = trans('admin.item_bin');
		$models = [];
		$item_id	=	isset($req->item_id)?trim($req->item_id):'';
		$item_sn	=	isset($req->item_sn)?trim($req->item_sn):'';
		$cat_id		=	isset($req->cat_id)?trim($req->cat_id):'';
		$com_id		=	isset($req->com_id)?trim($req->com_id):'';
		$brand_id	=	isset($req->brand_id)?trim($req->brand_id):'';
		$model_id	=	isset($req->model_id)?trim($req->model_id):'';
		$status		=	isset($req->status)?trim($req->status):'';
		$is_sale	=	isset($req->is_sale)?trim($req->is_sale):'';
		$is_hot		=	isset($req->is_hot)?trim($req->is_hot):'';
		$keyword	=	isset($req->keyword)?trim($req->keyword):'';
		$where 	 = ['items.is_show'=>1];
		
		
		if($item_id !== '')
		{
			$where   = array_merge($where, ['items.item_id' => $item_id]);
		}
		
		if($item_sn !== '')
		{
			$where   = array_merge($where, ['items.item_sn' => $item_sn]);
		}
		
		
		if($com_id !== '')
		{
			$where   = array_merge($where, ['items.com_id' => $com_id]);
		}
		
		if($brand_id !== '')
		{
			$where   = array_merge($where, ['items.brand_id' => $brand_id]);
			$models	 = Models::where('brand_id',$brand_id)->get();
		}
		
		if($model_id !== '')
		{
			$where   = array_merge($where, ['items.model_id' => $model_id]);
		}
		
		if($status !== '')
		{
			$where   = array_merge($where, ['items.status' => $status]);
		}
		
		if($is_sale !== '')
		{
			$where   = array_merge($where, ['items.is_sale' => $is_sale]);
		}
		
		if($is_hot !== '')
		{
			$where   = array_merge($where, ['items.is_hot' => $is_hot]);
		}
		
		if($cat_id !== '' && $keyword !== '')
		{
			$child = [$cat_id];
			$child = array_merge($child,(new Cates)->getChild($cat_id));
			$data = Items::leftJoin('cates', 'items.cat_id', '=', 'cates.cat_id')
			->leftJoin('brands', 'items.brand_id',  '=', 'brands.brand_id')
			->leftJoin('models', 'items.model_id',  '=', 'models.model_id')
			->leftJoin('companies', 'items.com_id', '=', 'companies.com_id')
			->select('items.*','brands.brand_name','models.model','cates.cat_name','companies.com_name')
			->where($where)
			->where('items.keyword','like','%'.$keyword.'%')
			->whereIn('cates.cat_id',$child)
			->orderBy('items.item_id','desc')
	        ->paginate($this -> pageSize);				
		}
		else if($cat_id !== '')
		{
			$child = [$cat_id];
			$child = array_merge($child,(new Cates)->getChild($cat_id));
			$data = Items::leftJoin('cates', 'items.cat_id', '=', 'cates.cat_id')
			->leftJoin('brands', 'items.brand_id',  '=', 'brands.brand_id')
			->leftJoin('models', 'items.model_id',  '=', 'models.model_id')
			->leftJoin('companies', 'items.com_id', '=', 'companies.com_id')
			->select('items.*','brands.brand_name','models.model','cates.cat_name','companies.com_name')
			->where($where)
			->whereIn('cates.cat_id',$child)
			->orderBy('items.item_id','desc')
	        ->paginate($this -> pageSize);				
		}
		else if($keyword !== '')
		{
			$data = Items::leftJoin('cates', 'items.cat_id', '=', 'cates.cat_id')
			->leftJoin('brands', 'items.brand_id',  '=', 'brands.brand_id')
			->leftJoin('models', 'items.model_id',  '=', 'models.model_id')
			->leftJoin('companies', 'items.com_id', '=', 'companies.com_id')
			->select('items.*','brands.brand_name','models.model','cates.cat_name','companies.com_name')
			->where($where)
			->where('items.keyword','like','%'.$keyword.'%')
			->orderBy('items.item_id','desc')
	        ->paginate($this -> pageSize);					
		}
		else
		{
			$data = Items::leftJoin('cates', 'items.cat_id', '=', 'cates.cat_id')
			->leftJoin('brands', 'items.brand_id',  '=', 'brands.brand_id')
			->leftJoin('models', 'items.model_id',  '=', 'models.model_id')
			->leftJoin('companies', 'items.com_id', '=', 'companies.com_id')
			->select('items.*','brands.brand_name','models.model','cates.cat_name','companies.com_name')
			->where($where)
			->orderBy('items.item_id','desc')
	        ->paginate($this -> pageSize);		
		}

		return view('admin.item.item_bin',['title'=>$title,
			'cates'		=>	$this->cates,
			'brands'	=>	$this->brands,
			'companies'	=>	$this->companies,
			'models'	=>  $models, 
			'data'		=>	$data,
			'item_id'	=>	$item_id,
			'item_sn'	=>	$item_sn,
			'cat_id'	=>	$cat_id	,
			'com_id'	=>	$com_id	,
		    'brand_id'	=>	$brand_id,
		    'model_id'	=>	$model_id,
			'status'	=>	$status	,
		    'is_sale'	=>	$is_sale,
			'is_hot'	=>	$is_hot	,
		    'keyword'	=>	$keyword,
		]);
	}
	
	
	
	
	
	
	/**
	 * 修改商品信息
	 */
	public function update(Request $req,$id)
	{
		//权限验证
		if(!in_array('item_edit',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
				
		if($req->isMethod('get'))
		{
			if(Items::where('items.item_id',$id)->count() < 1)
			{
				return redirect('admin/item');
			}
			$title  = trans('admin.item_update');
			$item 	= Items::where('item_id',$id)->first();
			$models	= Models::where('brand_id',$item->brand_id)->get();
			$cities	= City::where('province_id',$item->province_id)->get();
			$areas	= Area::where('city_id',$item->city_id)->get();
			$imgs	= Item_images::where('item_id',$id)->get();
			$attrs	= Item_attr::where('item_id',$id)->get();
			return view('admin.item.item_update',['title'=>$title,
				'cates'		=>	$this->cates,
				'brands'	=>	$this->brands,
				'companies'	=>	$this->companies,
				'province'  =>  $this->province,
				'models'	=>  $models,
				'item'		=>  $item,
				'imgs'		=>  $imgs,
				'attrs'		=>	$attrs,
				'cities'	=>	$cities,
				'areas'		=>	$areas,
			]);			
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'item_name' => 'required|max:100',
	            'cat_id'    => 'required|integer|not_in:0',
	            'number'    => 'required|integer',
	            'market_price'    => 'required|numeric',
	            'price'    		  => 'required|numeric',
	            'status'		  => 'required',
	            'is_sale'		  => 'required',
	            'is_hot'		  => 'required',
	        ];
	        $message = [
	            'item_name.required' => '商品名称不能为空',
				'item_name.max' 	 => '商品名称长度不能大于100',
				'cat_id.required' 	 => '请选择栏目',
				'cat_id.integer'	 => '栏目id为整型',
				'cat_id.not_in'		 => '栏目不能为顶级分类',
				'number.required' 	 => '库存不能为空',
				'number.integer'	 => '库存为数字',
				'market_price.required' => '市场价不能为空',
				'price.required' => '价格不能为空',
				'market_price.integer'	 => '市场价为数字',
				'market_price.integer'	 => '价格为数字',
				'status.required'		=>'请选择状态',
	            'is_sale.required'      =>'请选择是否上架',
	            'is_hot.required'       =>'请选择是否热销',		
	        ];
	
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			

			//更新商品数据
			$sn = $this->getSn($input);
			$desc = isset($input['desc'])?$input['desc']:'';
			Items::where('item_id',$id)
			->update(['item_name' => trim($req->item_name),
				'item_sn'		=> $sn,
				'cat_id'		=> trim($req->cat_id),
				'brand_id'		=> trim($req->brand_id),
				'com_id'		=> trim($req->com_id),
				'price' 		=> trim($req->price),
				'market_price' 	=> trim($req->market_price),
				'number' 		=> trim($req->number),
				'model_id' 		=> trim($req->model_id),
				'province_id' 	=> trim($req->province_id),
				'city_id' 		=> trim($req->city_id),
				'area_id' 		=> trim($req->area_id),
				'status' 		=> trim($req->status),
				'is_show' 		=> 0,
				'is_sale' 		=> trim($req->is_sale),
				'is_hot' 		=> trim($req->is_hot),
				'sort_order' 	=> trim($req->sort_order),
				'keyword' 		=> $this->getKeyword($input,$sn),
				'desc' 			=> $desc,
				'click' 		=> trim($req->click),
				'sales_number' 	=> trim($req->sales_number),
				'update_at'  	=> time()
			]);
			

			//商品图片处理
			$path = 'uploads/items/'.date('Y/m/d/');
			if(!is_dir($path))
			{
				mkdir($path,0777,true);
			}
			
			
			if(CS('watermark')!='' && CS('wm_switch') == 0)
			{
				foreach($input['img'] as $k => $i)
				{
					if($i != '')
					{
						$img_ori	 = Image::make($i);
				        $_oriPath    = $path.rand(1111,9999).'_'.strRand(4).'.jpg';
						$img_ori->insert(public_path(CS('watermark')), 'bottom-right');
		    			$img_ori->save($_oriPath);
		    			
						$img_big	 = Image::make($i)->resize(500, 500);
				        $_bigPath    = $path.rand(1111,9999).'_'.strRand(4).'_500x500'.'.jpg';
						$img_big->insert(public_path(CS('watermark')), 'bottom-right');
		    			$img_big->save($_bigPath);				
						
				        $img_little  = Image::make($i)->resize(200, 200);
				        $_littlePath = $path.rand(1111,9999).'_'.strRand(4).'_200x200'.'.jpg';
						$img_little->insert(public_path(CS('watermark')), 'bottom-right');
		    			$img_little->save($_littlePath);
		    			
		    			$img_tiny  = Image::make($i)->resize(100, 100);
				        $_tinyPath  = $path.rand(1111,9999).'_'.strRand(4).'_100x100'.'.jpg';
						$img_tiny->insert(public_path(CS('watermark')), 'bottom-right');
		    			$img_tiny->save($_tinyPath);
		    					
		    			Item_images::insert([
		    				'item_id' 		=> $id,
		    				'img_desc'		=> $input['img_desc'][$k],
		    				'ori_img' 		=> $_oriPath,
		    				'big_img'		=> $_bigPath,
		    				'little_img' 	=> $_littlePath,
		    				'tiny_img'		=> $_tinyPath,
		    			]);						
					}
				}					
			}
			else
			{					
				foreach($input['img'] as $k => $i)
				{
					if($i != '')
					{
						$img_ori	 = Image::make($i);
				        $_oriPath  = $path.rand(1111,9999).'_'.strRand(4).'.jpg';
		    			$img_ori->save($_oriPath);
		    			
						$img_big	 = Image::make($i)->resize(500, 500);
				        $_bigPath  = $path.rand(1111,9999).'_'.strRand(4).'_500x500'.'.jpg';
		    			$img_big->save($_bigPath);				
						
				        $img_little  = Image::make($i)->resize(200, 200);
				        $_littlePath  = $path.rand(1111,9999).'_'.strRand(4).'_200x200'.'.jpg';
		    			$img_little->save($_littlePath);
		    			
		    			$img_tiny  = Image::make($i)->resize(100, 100);
				        $_tinyPath  = $path.rand(1111,9999).'_'.strRand(4).'_100x100'.'.jpg';
		    			$img_tiny->save($_tinyPath);
		    					
		    			Item_images::insert([
		    				'item_id' 		=> $id,
		    				'img_desc'		=> $input['img_desc'][$k],
		    				'ori_img' 		=> $_oriPath,
		    				'big_img'		=> $_bigPath,
		    				'little_img' 	=> $_littlePath,
		    				'tiny_img'		=> $_tinyPath,
		    			]);						
					}
				}				
			}
			
			//商品属性处理
			foreach($input['attr_name'] as $k => $v)
			{	if($v != '')
				{
	    			Item_attr::insert([
    					'item_id' 		=> $id,
						'attr_name'		=> $v,
						'attr_value'   	=> $input['attr_value'][$k],
    				]);		
				}			
			}
			
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.update_succ'),
				'url' => url('admin/item')
			]);
			
			
			
		}

	}
	
	


	/**
	 *	将商品放入回收站 	
	 */
	public function itemDel($id)
	{
		//权限验证
		if(!in_array('item_del',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		if(Items::where('item_id',$id)->count() > 0)
		{
			Items::where('item_id',$id)->update(['is_show' => 1]);
			return redirect('admin/item');
		}
	}
	
	
	
	
	/**
	 * 从回收站恢复商品
	 */
	public function itemRecover($id)
	{
		//权限验证
		if(!in_array('item_recover',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		if(Items::where('item_id',$id)->count() > 0)
		{
			Items::where('item_id',$id)->update(['is_show' => 0]);
			return redirect('admin/itemBin');
		}		
	}
	
	
	
	
	
	
	/**
	 * 彻底删除一个商品
	 */
	public function itemDelTrue($id)
	{
		//权限验证
		if(!in_array('item_del_true',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}

		if(Items::where('item_id',$id)->count() > 0)
		{
			//删除该商品所有的图片
			$item_imgs = Item_images::where('item_id',$id)->select('img_id')->get();
			if($item_imgs != '')
			{
				foreach($item_imgs as $i)
				{
					$imgs = Item_images::where('img_id',$i->img_id)->select('ori_img','big_img','little_img','tiny_img')->first();
					if($imgs != '')
					{
						$ori_img 	= public_path($imgs -> ori_img);
						$big_img 	= public_path($imgs -> big_img);
						$little_img = public_path($imgs -> little_img);
						$tiny_img 	= public_path($imgs -> tiny_img);	
						if(unlink($ori_img)&&unlink($big_img)&&unlink($little_img)&&unlink($tiny_img))
						{
							Item_images::where('img_id',$i->img_id)->delete();
						}			
					}		
				}		
			}
			
			//删除商品的所有属性
			if(Item_attr::where('item_id',$id)->count() > 0)
			{
				Item_attr::where('item_id',$id)->delete();
			}
	
			Items::where('item_id',$id)->delete();
			
			return redirect('admin/itemBin');
		}
	}
	
	


	/**
	 * 查询指定省份下的市
	 */
	public function getCityByProvince(Request $req)
	{
		return City::where('province_id',$req->province_id)->get();
	}



	/**
	 * 查询指定市下的区县
	 */
	public function getAreaByCity(Request $req)
	{
		return Area::where('city_id',$req->city_id)->get();
	}




	
	/**
	 * 生成item_sn
	 */
	public function getSn($input,$num = 4)
	{
		if($input['item_sn'] == '')
		{
			return date('Ymd').mt_rand(1111,9999).'_'.strRand($num);	
		}
		else
		{
			return $input['item_sn'];
		}
		
	}


	
	/**
	 * 生成关键字
	 */
	public function getKeyword($input,$sn)
	{
		if($input['keyword'] == '')
		{
			if($input['cat_id']!=0)
			{
				$cat = Cates::where('cat_id',$input['cat_id'])->select('cat_name')->first()->cat_name;
			}
			else
			{
				$cat = '';
			}
			
			if($input['com_id'] !== '')
			{
				$com = Companies::where('com_id',$input['com_id'])->select('com_name')->first()->com_name;
			}
			else
			{
				$com = '';
			}
			
			if(isset($input['model_id']) && $input['model_id'] !== '')
			{
				$model = Models::where('model_id',$input['model_id'])->select('model')->first()->model;	
			}
			else
			{
				$model = '';
			}
			
			if($input['brand_id'] !== '')
			{
				$brand = Brands::where('brand_id',$input['brand_id'])->select('brand_name')->first()->brand_name;	
			}
			else
			{
				$brand = '';
			}
				
			return $input['item_name'].' '.$sn.(new Cates)->getParentKeyword($input['cat_id']).$cat.' '.$model.' '.$brand.' '.$com;
		}
		else
		{
			return $input['keyword'];
		}
	}




	
	/**
	 * 商品批量操作接口
	 */
	public function itemHandle(Request $req)
	{
		//批量加入回收站
		if($req->act == 'del')
		{
			$in = array_flatten($req->items);
			Items::whereIn('item_id',$in)
            ->update(['is_show' => 1]);
			return ['error'=>0,'message'=>'success'];
		}
	
		//批量恢复
		if($req->act == 'recover')
		{
			$in = array_flatten($req->items);
			Items::whereIn('item_id',$in)
            ->update(['is_show' => 0]);
			return ['error'=>0,'message'=>'success'];
		}

		//批量删除
		if($req->act == 'del_true')
		{
			$in = array_flatten($req->items);
			//删除该商品所有的图片
			$item_imgs = Item_images::whereIn('item_id',$in)->select('img_id')->get();
			if($item_imgs != '')
			{
				foreach($item_imgs as $i)
				{
					$imgs = Item_images::where('img_id',$i->img_id)->select('ori_img','big_img','little_img','tiny_img')->first();
					if($imgs != '')
					{
						$ori_img 	= public_path($imgs -> ori_img);
						$big_img 	= public_path($imgs -> big_img);
						$little_img = public_path($imgs -> little_img);
						$tiny_img 	= public_path($imgs -> tiny_img);	
						if(unlink($ori_img)&&unlink($big_img)&&unlink($little_img)&&unlink($tiny_img))
						{
							Item_images::where('img_id',$i->img_id)->delete();
						}			
					}		
				}		
			}
	
			//删除商品的所有属性
			if(Item_attr::whereIn('item_id',$in)->count() > 0)
			{
				Item_attr::whereIn('item_id',$in)->delete();
			}
	
			Items::whereIn('item_id',$in)->delete();
		
			return ['error'=>0,'message'=>'success'];
		}
	
		//批量上架
		if($req->act == 'on_sale')
		{
			$in = array_flatten($req->items);
			Items::whereIn('item_id',$in)
            ->update(['is_sale' => 0]);
			return ['error'=>0,'message'=>'success'];
		}
		
		//批量下架
		if($req->act == 'sale_out')
		{
			$in = array_flatten($req->items);
			Items::whereIn('item_id',$in)
            ->update(['is_sale' => 1]);
			return ['error'=>0,'message'=>'success'];
		}
		
		//批量审核通过
		if($req->act == 'pass')
		{
			$in = array_flatten($req->items);
			Items::whereIn('item_id',$in)
            ->update(['status' => 0]);
			return ['error'=>0,'message'=>'success'];
		}
		
		//批量审核不通过
		if($req->act == 'unpass')
		{
			$in = array_flatten($req->items);
			Items::whereIn('item_id',$in)
            ->update(['status' => 2]);
			return ['error'=>0,'message'=>'success'];
		}
		
	}
	

	
	
	/**
	 *	删除商品单张图片 
	 */	
	public function imgDel(Request $req)
	{
		$imgs = Item_images::where('img_id',$req->img_id)->select('ori_img','big_img','little_img','tiny_img')->first();
		
		if($imgs != '')
		{
			$ori_img 	= public_path($imgs -> ori_img);
			$big_img 	= public_path($imgs -> big_img);
			$little_img = public_path($imgs -> little_img);
			$tiny_img 	= public_path($imgs -> tiny_img);
			
			if(unlink($ori_img)&&unlink($big_img)&&unlink($little_img)&&unlink($tiny_img))
			{
				Item_images::where('img_id',$req->img_id)->delete();
				return ['error'=>0,'message'=>'success'];
			}			
		}
			
	} 
	
	
	/**
	 * 修改图片描述
	 */
	public function imgDescUpdate(Request $req)
	{
		if(Item_images::where('img_id',$req->img_id)->count() > 0)
		{
			Item_images::where('img_id',$req->img_id)->update(['img_desc' => $req->desc]);
			return ['error'=>0,'message'=>'success'];	
		}
		
	}
	
	
	/**
	 * 删除商品单条属性 
	 */
	public function attrDel(Request $req)
	{
		if(Item_attr::where('attr_id',$req->attr_id)->count() > 0)
		{
			Item_attr::where('attr_id',$req->attr_id)->delete();
			return ['error'=>0,'message'=>'success'];	
		}
	}


	/**
	 * 修改商品单条属性 
	 */
	public function attrUpdate(Request $req)
	{
		if(Item_attr::where('attr_id',$req->attr_id)->count() > 0)
		{
			if($req->act == 'attr_name')
			{
				Item_attr::where('attr_id',$req->attr_id)->update(['attr_name'=>$req->value]);
				return ['error'=>0,'message'=>'success'];					
			}
	
			if($req->act == 'attr_value')
			{
				Item_attr::where('attr_id',$req->attr_id)->update(['attr_value'=>$req->value]);
				return ['error'=>0,'message'=>'success'];					
			}
			
		}	
	}



	/**
	 * 分类列表
	 */
	public function cateList(Request $req)
	{
		showc();
		//权限验证
		if(!in_array('item_cate_list',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}

		$title =  trans('admin.item_cate');
		
		return view('admin.item.cate_list',[
			'title'	=> $title,
			'data' => $this->cates,
		]);
		
	}


	/**
	 * 分类添加
	 */
	public function cateAdd(Request $req)
	{
		//权限验证
		if(!in_array('item_cate_add',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}

		if($req->isMethod('get'))
		{
			$title 	= trans('admin.cate_add');				
			return view('admin.item.cate_add',['title'=>$title,
				'cates'		=>	$this->cates,		
			]);
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'parent_id'   => 'required|integer',
	            'cat_name'    => 'required|max:50',
	            'unit'    	  => 'required|max:10',
				'is_show'	  => 'required|in:0,1',
				'sort_order'  => 'integer',
				'desc'		  => 'max:200',
	        ];
			
	        $message = [
	            'parent_id.required' 	=> '上级分类不能为空',
				'parent_id.integer'		=> '上级分类为整数',
				'cat_name.required'		=> '分类名称是必须的',
				'cat_name.max'			=> '分类名称长度不能大于50',
				'unit.required'			=> '单位名称是必须的',
				'unit.max'				=> '单位名称长度不能大于10',
				'is_show.required'		=> '显示状态是必须的',
				'is_show.in'			=> '请选择“是”或“否”',
				'sort_order.integer'	=> '排序为整数',
				'desc.max'				=> '描述长度不能大于200',
				

	        ];
	
	        $validate = Validator::make($input,$rule,$message);
			
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			Cates::insert(['parent_id' => trim($req->parent_id),
				'cat_name'		=> trim($req->cat_name),
				'unit'			=> trim($req->unit),
				'is_show' 		=> trim($req->is_show),
				'sort_order' 	=> trim($req->sort_order),
				'desc' 			=> trim($req->desc),
			]);
			
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.add_succ'),
				'url' => url('admin/itemCate'),
			]);					
		}

	}




	/**
	 * 分类修改
	 */
	public function cateUpdate(Request $req,$id)
	{
		//权限验证
		if(!in_array('item_cate_edit',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		//判断是分类否存在
		if(Cates::where('cat_id',$id)->count() < 1)
		{
			return redirect('admin/artcleCate');
		}

		if($req->isMethod('get'))
		{
			$title 	= trans('admin.cate_add');	
			$cate	= Cates::where('cat_id',$id)->first();			
			return view('admin.item.cate_update',['title'=>$title,
				'cates'		=>	$this->cates,
				'cate'		=>  $cate		
			]);
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'parent_id'   => 'required|integer',
	            'cat_name'    => 'required|max:50',
              	'unit'    	  => 'required|max:10',
				'is_show'	  => 'required|in:0,1',
				'sort_order'  => 'integer',
				'desc'		  => 'max:200',
	        ];
			
	        $message = [
	            'parent_id.required' 	=> '上级分类不能为空',
				'parent_id.integer'		=> '上级分类为整数',
				'cat_name.required'		=> '分类名称是必须的',
				'cat_name.max'			=> '分类名称长度不能大于50',
				'unit.required'			=> '单位名称是必须的',
				'unit.max'				=> '单位名称长度不能大于10',
				'is_show.required'		=> '显示状态是必须的',
				'is_show.in'			=> '请选择“是”或“否”',
				'sort_order.integer'	=> '排序为整数',
				'desc.max'				=> '描述长度不能大于200',
				
	        ];
	
	        $validate = Validator::make($input,$rule,$message);
			
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			Cates::where('cat_id',$id)
			->update(['parent_id' => trim($req->parent_id),
				'cat_name'		=> trim($req->cat_name),
				'unit'			=> trim($req->unit),
				'is_show' 		=> trim($req->is_show),
				'sort_order' 	=> trim($req->sort_order),
				'desc' 			=> trim($req->desc),
			]);
			
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.update_succ'),
				'url' => url('admin/itemCate'),
			]);		
		}

	}
	
	
	/**
	 * 分类删除 
	 */
	public	function  cateDel(Request $req)
	{
		//权限验证
		if(!in_array('item_cate_del',session('access')))
		{
			return [
				'error'=>1,
				'message'=>'fail',
				'content'=>'没有该操作的权限！',
			];
		}
		
		
		//判断分类下是否有子级
		$cates = Cates::where('parent_id',$req->id)->count();
		if($cates > 0)
		{
			return [
				'error'=>1,
				'message'=>'fail',
				'content'=>'该分类下还有子分类，请删除后再试！',
			];		
		}
		

		//判断分类下是否有商品
		$child = [$req->id];
		$child = array_merge($child,(new Cates)->getChild($req->id));
		$count  = Items::whereIn('cat_id',$child)->count();
		if($count > 0)
		{
			return [
				'error'=>1,
				'message'=>'fail',
				'content'=>'该分类下还有'.$count.'个商品，请删除商品后再试！',
			];
		}

		if(Cates::where('cat_id',$req->id)->count() > 0)
		{
			Cates::where('cat_id',$req->id)->delete();
			return [
				'error'  =>0,
				'message'=>'success',
				'content'=>'删除成功！',
			];
		}
		

	}
	
	
	
	/**
	 * 商品批量上传
	 */
	public function batchUpload(Request $req)
	{		
		//权限验证
		if(!in_array('item_import',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		if($req->isMethod('get'))
		{
			$title = trans('admin.item_batch_upload');
			return view('admin.item.batch',[
				'title' 	=> 	$title,
				'cates'		=>	$this->cates,
				'brands'	=>	$this->brands,
				'province'  =>  $this->province,
			]);
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'excel'   => 'required',
				'cat_id'  => 'required|integer|not_in:0',
	        ];
			
	        $message = [
	            'excel.required' 	 => '请上传表格',
	            'cat_id.required' 	 => '请选择栏目',
				'cat_id.integer'	 => '栏目id为整型',
				'cat_id.not_in'		 => '栏目不能为顶级分类',		
	        ];
	
	        $validate = Validator::make($input,$rule,$message);
			
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			$file = excelUpload('items',$req);
			
			$cat_id 	= isset($req -> cat_id)?$req -> cat_id:0;
			$brand_id 	= isset($req -> brand_id)?$req -> brand_id:0;
			$model_id 	= isset($req -> model_id)?$req -> model_id:0;
			
			$res = Excel::load($file, function($reader){})->toArray();
			
			$sn = date('Ymd').mt_rand(1111,9999).'_'.strRand(4);
			
			
			foreach($res as $k => $v)
			{
				$input['item_name']	= $v[0];
				$input['cat_id']	= $cat_id;
				$input['brand_id']	= $brand_id;
				$input['model_id']	= $model_id;
				$input['com_id']	= '';
				$input['keyword']	= '';
				Items::insert([
					'cat_id'	=>   $cat_id,
					'brand_id'	=>   $brand_id,
					'model_id'	=>   $model_id,
					'item_name' => 	$v[0],
					'item_sn'	=> 	$sn,
					'number'	=>	$v[1],
					'price'		=>	$v[2],
					'market_price'	=>	$v[3],
					'is_hot'		=>	$v[4],
					'is_sale'		=>	$v[5],
					'desc'			=>	$v[6],
					'sales_number'	=>	$v[7],
					'click'			=>	$v[8],
					'province_id' 	=> 	$req->province_id,
  					'city_id'		=>  $req->city_id,
  					'area_id' 		=> 	$req->area_id,
  					'keyword'		=>  $this->getKeyword($input,$sn),
				]);
			}

  			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.import_succ'),
				'url' => url('admin/item'),
			]);	
			
		}		
	}





}
